package com.example.lxy.controller;

import com.alibaba.fastjson.JSON;
import com.example.lxy.pojo.access;
import com.example.lxy.pojo.role;
import com.example.lxy.pojo.roleaccess;
import com.example.lxy.service.AccessService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


@Controller
@ResponseBody
@Api(value = "权限管理",tags = "权限接口模块")
public class AccessController {
    @Autowired
    private AccessService accessService;

    @CrossOrigin
    @PostMapping(value = "/api/listaccess")
    @ApiOperation(value = "查询出所有权限",notes = "在点击增加权限时查询所有权限")
    public String list() {
        HashMap<String, Object> data = new HashMap<>();
        List<access> list = accessService.list();
        if (list == null) {
            data.put("flag", 400);
        } else {
            data.put("logg", list);
            data.put("flag", 200);
        }
        String s = JSON.toJSONString(data);
        return s;
    }

    @CrossOrigin
    @PostMapping(value = "/api/listid")
    @ApiOperation(value = "根据rid查询出该角色的权限",notes = "根据RID查询，实际上是权限表的ID，只不过是通过中间表来实现的")
    public String listid(@RequestBody role r) {
        HashMap<String, Object> data = new HashMap<>();
        List<role> listid = accessService.listid(r.getRid());
        if (listid == null) {
            data.put("flag", 400);
        } else {
            data.put("logg", listid);
            data.put("flag", 200);
        }
        String s = JSON.toJSONString(data);
        return s;
    }

    @CrossOrigin
    @PostMapping(value = "/api/delroleaccess")
    @ApiOperation(value = "批量删除权限",notes = "根据中间表roleaccess中的主键chaojiid来实现批量删除")
    public int plsc(@RequestParam(required = true) String chaojiid) {
        List idList = new ArrayList();
        String[] strs = chaojiid.split(",");
        for (String str : strs) {
            idList.add(str);
        }
        return accessService.deleteUserAllById(idList);
    }

    @CrossOrigin
    @PostMapping(value = "/api/insertaccess")
    @ApiOperation(value = "增加权限",notes = "由于接值存在一定的BUG，所有前端请求参数使用了拼接")
    public String plinset(HttpServletRequest httpServletRequest) {
        Integer roleid = new Integer(httpServletRequest.getParameter("roleid"));
        System.out.println(roleid);
        Integer accessid = new Integer(httpServletRequest.getParameter("accessid"));
        System.out.println(accessid);
        roleaccess roleaccess = new roleaccess();
        roleaccess.setRoleid(roleid);
        roleaccess.setAccessid(accessid);
        accessService.adds(roleaccess);
        return "true";
    }
}
